import urllib
import random

from tornado.options import options

from libs.tools.widget import Common
from libs.base.model import BaseModel
from libs.base.async_request import Requests


class SMSModel(BaseModel):

    def __init__(self, handler):
        super(SMSModel, self).__init__(handler)
        self.handler = handler
        self.data = {}

    async def send_login_code(self, phone_number):
        random_code = random.randint(1000, 9999)
        self.redis.set("login_msg_code", random_code, {"mobile": phone_number})
        url = "http://send.18sms.com/msg/HttpBatchSendSM"
        headers = {
            "Content-type": "application/x-www-form-urlencoded",
            "Accept": "text/plain"
        }
        msg = '验证码：{code}，用于登录永乐管理后台，5分钟内有效，请尽快完成操作'
        params = {
            'account': options.config["sms_account"],
            'pswd': options.config["sms_password"],
            'msg': msg.format(code=random_code),
            'mobile': phone_number,
            'needstatus': 'true',
            'extno': '',
            'resptype': 'json'
        }
        data = urllib.parse.urlencode(params)
        res = await Requests.post(url, headers=headers, json=data)
        body = Common.json_loads(res.body)
        if body.get("result") == 0:
            # 发送成功
            return 0
        # 发送失败
        return 4005

    def check_login_code(self, phone_number, code):
        # 测试方案
        if not options.config["check_sms_status"]:
            return True
        cache_code = self.redis.get("login_msg_code", {"mobile": phone_number})
        if cache_code and cache_code == code:
            return True
        return False
